<template>
  <div class="login">
    <div class="login-container">
      <div class="login-title">云上博物馆后台系统</div>
      <el-form :rules="loginrules" :model="loginform" class="form">
        <!-- 用户名 -->
        <el-form-item prop="username">
          <el-input v-model="loginform.username" placeholder="请输入用户名">
            <template #prefix>
              <el-icon><User /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <!-- 密码 -->
        <el-form-item prop="password">
          <el-input
            v-model="loginform.password"
            placeholder="请输入密码"
            type="password"
            show-password
          >
            <template #prefix>
              <el-icon><Unlock /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <!-- 登录按钮 -->
        <el-form-item>
          <el-button type="primary" @click="login">登录</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { userLogin } from '@/api/user'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
const route = useRouter()
const loginform = ref({})
const login = async () => {
  const { data } = await userLogin(loginform.value)
  console.log(data)
  if (data.token) {
    window.localStorage.setItem('token', data.token)
    window.localStorage.setItem('userInfo', JSON.stringify(loginform.value.username))
    ElMessage.success('登录成功')
    await route.push('/')
  }
}

//添加校验
const loginrules = ref({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 10, message: '用户名长度在3到10个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 15, message: '密码长度在6到15个字符', trigger: 'blur' }
  ]
})
</script>

<style lang="scss" scoped>
.login {
  position: relative;
  height: 100vh;
  width: 100vw;
  background: linear-gradient(to bottom, #007bff, #ffffff);

  .login-container {
    position: absolute;
    width: 20vw;
    height: 30vh;
    right: 20vh;
    top: 30vh;
    background: rgba(0, 0, 0, 0.2);
    border-radius: 20px;

    .login-title {
      line-height: 20px;
      text-align: center;
      font-size: 20px;
      font-weight: 600;
      margin: 20px;
    }
    .form {
      width: 80%;
      margin: 0 auto;
      button {
        width: 60%;
        margin: 0 auto;
      }
    }
  }
}
</style>
